package com.hcy.app.screen.relax

import android.content.Context
import android.text.TextPaint
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hcy.app.utils.FileUtils
import com.hcy.app.utils.SimpleSnowflake
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.io.File
import java.nio.charset.Charset
import javax.inject.Inject

@HiltViewModel
class RelaxViewModel @Inject constructor(
    private val fileInfoDao: RelaxFileInfoDao
) : ViewModel(){

    val generator = SimpleSnowflake(workerId = 1)

    private val _relaxState = MutableStateFlow(RelaxState())
    val relaxState =  _relaxState.asStateFlow()

    private inline fun updateState(transform: RelaxState.() -> RelaxState) {
        _relaxState.update{ state -> state.transform() }
    }

    init {
        loadFileList()
    }

    fun loadFileList(){
        viewModelScope.launch (Dispatchers.IO) {
            try {
                // 加载配置
                updateState { copy(supportFileType = setOf("txt","mp4"))  }

                // 加载文件
                val li = fileInfoDao.findAll()
                updateState{ copy( fileList = li ) }
            }catch (e: Exception){
                Log.e("miao",e.toString())
            }
        }
    }


    // 删除文件
    fun deleteFile(filepath: String){
        viewModelScope.launch (Dispatchers.IO) {
            fileInfoDao.deleteByPath(filepath)
            try {
                File(filepath).delete()
            }catch (e: Exception){
                Log.e("miao",e.stackTraceToString())
            }
        }
    }

    // 更新进度
    fun updateProgress(fileId: Long?, prog: Long) {
        viewModelScope.launch (Dispatchers.IO) {
            fileInfoDao.updateProgress(fileId,prog)
            updateState{ copy( currentIndex = prog ) }
            Log.d("miao","当前进度：${_relaxState.value.currentIndex},传入进度：${prog}")
        }
    }

    // 更新文件隐藏状态
    fun updateShow(fileId: Long?,isPrivate: Boolean){
        viewModelScope.launch (Dispatchers.IO) {
            fileInfoDao.updatePrivate(fileId,isPrivate)
            updateState{ copy( fileList = fileInfoDao.findAll() ) }
        }
    }

    // 重新加载文件列表，更新数据库
    fun reloadFileList(ctx: Context){
        viewModelScope.launch (Dispatchers.IO) {
            val fileList = scanRelaxFileList(ctx)
            val dbLi = fileInfoDao.findAll()
            val dbFiles = mutableListOf<File>()
            dbLi.forEach { dbFiles.add(File(it.filePath)) }
            var isChange=false
            (fileList-dbFiles).forEach {
                isChange = true
                // 添加到数据库中
                fileInfoDao.insert(
                    RelaxFileInfo(id=generator.nextId(), name = it.name,
                        filePath = it.path, fileType = it.extension, createdAt = System.currentTimeMillis()/1000,
                        isPrivate = false, currentIndex = 0L
                    )
                )
            }
            (dbFiles-fileList).forEach {
                isChange = true
                // 从数据库中移除
                fileInfoDao.deleteByPath(it.path)
            }
            if (isChange){
                updateState{ copy( fileList = fileInfoDao.findAll() ) }
            }
        }
    }

    // 扫描文件
    private fun scanRelaxFileList(ctx:Context): List<File>{
        val fileType = setOf("txt","mp4")// 支持的文件格式

        val fileList= FileUtils.getPrivateExternal(ctx,fileType)
        val videos = FileUtils.getVideoInfo(ctx)

        // 测试数据
        val li= (fileList+videos).toMutableList()
        li.add(File("西游记.txt"))
        li.add(File("西游记2.txt"))
        li.add(File("葫芦娃.mp4"))
        li.add(File("葫芦娃2.mp4"))
        return li.toList()
    }

    fun setCurrentFile(info:RelaxFileInfo){
        updateState { copy( currentFile = info ) }
        updateState { copy( currentIndex = info.currentIndex ) }
        Log.d("miao","setCurrentFile 当前文件：${_relaxState.value.currentFile},下标：${relaxState.value.currentIndex}")
    }

    fun readTextFile(screenWidth: Int, maxLines: Int,paint: TextPaint): List<String>{
        try {
            Log.d("miao","readTextFile 当前文件：${_relaxState.value.currentFile},下标：${relaxState.value.currentIndex}")
            val currentFile = File(_relaxState.value.currentFile?.filePath.toString())
            val fullText = currentFile.readText(charset =Charset.forName("GBK"))
            return TextPaging.getPages(fullText,screenWidth, maxLines,paint)
        }catch (e: Exception){
            Log.d("miao",e.toString())
            return emptyList()
        }

    }





}

data class RelaxState(
    val currentFile : RelaxFileInfo?=null,
    val fileList: List<RelaxFileInfo> = emptyList<RelaxFileInfo>(), // 文件列表
    val currentIndex : Long = 0L,// 当前进度
    val privatePwd : String = "1111", // 私有管理密码
    val supportFileType: Set<String> = emptySet<String>() // 支持的文件类型
)


